class_name SoundCollider extends Area3D

@export var speed_of_sound:float = 340.0
@export var max_bounce_time:int = 0
@export var sound:AudioStream

var max_life_time:int = 256
var velocity:Vector3
var sound_emmited:bool = false
var sound_heard:bool = false
var life_time:int = 0
var collision_shape:CollisionShape3D
var sound_player:AudioStreamPlayer3D 

func _ready() -> void:
	init()

func init() -> void:
	life_time = max_life_time
	collision_shape = CollisionShape3D.new()
	add_child(collision_shape)
	collision_shape.shape = SphereShape3D.new()
	collision_shape.shape.radius = 0.0
	sound_player = AudioStreamPlayer3D.new()
	sound_player.doppler_tracking = 2
	add_child(sound_player)
	body_entered.connect(on_body_entered)
	

func _physics_process(delta: float) -> void:
	if sound_emmited:
		collision_shape.shape.radius += speed_of_sound/128.0
	if sound_heard:
		sound_player.position += velocity*delta
	life_time -= 1
	if life_time <= 0:
		queue_free()

func on_body_entered(_body) -> void:
	sound_player.stream = sound
	sound_player.play()
	sound_heard = true

func emit_sound() -> void:
	sound_emmited = true
